package com.ias.agdis_r.service;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.DisplayMetrics;

import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.util.sdcard.WriteLog;

import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;

@SuppressLint("SimpleDateFormat")
public class GpsService {

	protected Context context;
	private boolean bUpload = true;
	private long lNewDataTime = 0, lSaveDataTime = 0;
	private long lCollectInterval = 3 * 1000;
	private LocationManager locationManager = (LocationManager) DataBaseManager.getInstance().getContext().getSystemService(Context.LOCATION_SERVICE);
	private GpsStatus gpsStatus = null;

	public GpsService(Context context) {
		this.context = context;
		long value = 1000 * DataBaseManager.getInstance().getLong(ParameterModel.T_GPS_INFO, ParameterModel.COLLECT_INTERVAL);
		if (value != 0) {
			lCollectInterval = value;
		}
	}

	/** 移除监听 */
	public void removeGPSListener() {
		if (locationManager != null) {
			if (statusListener != null) {
				locationManager.removeGpsStatusListener(statusListener);
			}
			if (locationListener != null) {
				locationManager.removeUpdates(locationListener);
			}
		}
	}

	/**
	 * 启动gps
	 */
	public void startGPS() {
		try {
			// 获取GPS信息 获取位置提供者provider中的位置信息
			locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), true));// 获取最好的提供者
			// 第一次获得设备的位置
//			updateToNewLocation(location);

			// 设置监听器，自动更新的最小时间为间隔N秒(1秒为1*1000，这样写主要为了方便)或最小位移变化超过N米
			// 实时获取位置提供者provider中的数据，一旦发生位置变化 立即通知应用程序locationListener
			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
			locationManager.addGpsStatusListener(statusListener);
			WriteLog.getInstance().writeDebugLog("GpsService|startGPS()");
		} catch (Exception e) {
			e.printStackTrace();
			WriteLog.getInstance().writeDebugLog("GpsService|startGPS failed,Exception:" + e.getMessage());
		}
	}
	private String getFormatTime(Location location){
		long GpsTime = location.getTime();
		Date date = new Date(GpsTime);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
		String time = sdf.format(date).toString();
		return time;
	}
	// 定位监听类负责监听位置信息的变化情况
	private Location lastLocation;
	private final LocationListener locationListener = new LocationListener() {

		// 当位置改变时调用下面的函数
		public void onLocationChanged(Location location) {

			if (lastLocation != null) {
				String time = getFormatTime(location);
				String ltime = getFormatTime(lastLocation);
				if (time.equals(ltime)) {
					lastLocation = location;
					return;
				}

			}
			lastLocation = location;
			updateToNewLocation(location);
			WriteLog.getInstance().writeDebugLog("GpsService|onLocationChanged()");
		}

		public void onProviderDisabled(String provider) {
			updateToNewLocation(null);
			WriteLog.getInstance().writeDebugLog("GpsService|onProviderDisabled()");
		}

		public void onProviderEnabled(String provider) {
			WriteLog.getInstance().writeDebugLog("GpsService|onProviderEnabled()");
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			WriteLog.getInstance().writeDebugLog("GpsService|onStatusChanged()");
		}
	};

	// Status 响应函数，当接收到的卫星的参数发生改变时，就会调用下面的响应函数
	// 添加监听卫星
	private final GpsStatus.Listener statusListener = new GpsStatus.Listener() {

		@Override
		public void onGpsStatusChanged(int event) {
			// 获取GPS卫星信息，与获取location位置信息一样，还是通过locationManager类，方法为getGpsStatus，返回的是一个GpsStatus类型的结构
			gpsStatus = locationManager.getGpsStatus(null);
			// 触发事件event
			switch (event) {
			case GpsStatus.GPS_EVENT_STARTED:

				break;
			// 第一次定位时间
			case GpsStatus.GPS_EVENT_FIRST_FIX:

				break;
			// 收到卫星信息，并调用DrawMap()函数，进行卫星信号解析并显示到屏幕上
			case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
				// DrawMap();

				break;

			case GpsStatus.GPS_EVENT_STOPPED:
				break;
			}
		}
	};

	private int heightp;
	private int widthp;

	protected void DrawMap() {
		int i = 0;
		float[] alimuth = null;
		float[] elevation = null;
		float[] snr = null;
		// 获取屏幕信息，dm为DisplayMetrics类型的变量
		DisplayMetrics dm = new DisplayMetrics();
		((Activity) DataBaseManager.getInstance().getContext())
				.getWindowManager().getDefaultDisplay().getMetrics(dm); // 调用这三个函数将屏幕信息保存在dm中
		heightp = dm.heightPixels; // 手机屏幕高度
		widthp = dm.widthPixels; // 手机屏幕宽度

		// 获取卫星信息，gpsStatus为卫星响应函数中获得的卫星GpsStatus类型变量
		Iterable<GpsSatellite> allSatellites = gpsStatus.getSatellites();
		Iterator<GpsSatellite> Iteratorsate = allSatellites.iterator();
		// 遍历获取每颗卫星的信息
		while (Iteratorsate.hasNext()) {
			GpsSatellite satellite = Iteratorsate.next();
			alimuth[i] = satellite.getAzimuth(); // 坐标方位角
			elevation[i] = satellite.getElevation(); // 卫星仰角
			snr[i] = satellite.getSnr();
			i++;
		}
	}

	// 显示GPS位置信息，location响应函数中，当location发生变化时调用下面的函数
	private void updateToNewLocation(Location location) {
		lNewDataTime = System.currentTimeMillis();

		if (location != null) {
			String bear = location.getBearing() + ""; 				// 偏离正北方的度数
			String latitude = (float) location.getLatitude() + ""; 	// 维度
			String longitude = (float) location.getLongitude() + "";// 经度
			float GpsSpeed = location.getSpeed() * 3.6f; 		// 速度: Km/h

			// 设置时间的显示格式 yyyyMMddHHmmss 20081101120101
			long GpsTime = location.getTime(); // 时间
			Date date = new Date(GpsTime); // 利用Date进行时间的转换
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String time = sdf.format(date).toString();

			try {
				HashMap<Object, Object> info = new HashMap<Object, Object>();
				info.put(ParameterModel.GPS_BEAR, bear);
				info.put(ParameterModel.GPS_LATITUDE, latitude);
				info.put(ParameterModel.GPS_LONGITUDE, longitude);
				info.put(ParameterModel.GPS_SPEED, GpsSpeed);
				info.put(ParameterModel.GPS_TIME, time);
				if (lNewDataTime-lSaveDataTime > lCollectInterval) {
					bUpload = true;
					lSaveDataTime = lNewDataTime;
				} else {
					bUpload = false;
				}
				JavaBeanManager.getInstance().saveGpsData(info,bUpload);
				WriteLog.getInstance().writeDebugLog("GpsService|Map:" + DataManager.getInstance().getMapper().writeValueAsString(info));
			} catch (Exception e) {
				e.printStackTrace();
				WriteLog.getInstance().writeDebugLog("GpsService|updateToNewLocation failed,Exception:" + e.getMessage());
			}
		}
	}
}
